package com.yoyo.yyadsdk.util;

import com.anye.greendao.gen.AdvScreenEntityDao;
import com.anye.greendao.gen.DaoSession;
import com.anye.greendao.gen.LocalPullEntityDao;
import com.anye.greendao.gen.PullEntityDao;
import com.anye.greendao.gen.PushEntityDao;
import com.yoyo.yyadsdk.bean.dao.LocalPullEntity;
import com.yoyo.yyadsdk.bean.dao.MonitorTimeEntity;
import com.yoyo.yyadsdk.bean.dao.PullEntity;
import com.yoyo.yyadsdk.bean.dao.RuleListEntity;

import java.util.ArrayList;
import java.util.List;

class PullType {
    private int mActionType;
    private long mLastTime;
    private List<PullEntity> mPullEntities;
    private List<LocalPullEntity> mLocalPullEntityList;
    private List<RuleListEntity> mRuleListEntityList;

    PullType(int actionType) {
        mActionType = actionType;
    }

    List<PullEntity> getPullEntities() {
        return mPullEntities;
    }

    List<LocalPullEntity> getLocalPullEntityList() {
        return mLocalPullEntityList;
    }

    List<RuleListEntity> getRuleListEntityList() {
        return mRuleListEntityList;
    }

    long getLastTime() {
        return mLastTime;
    }

    PullType invoke() {
        DaoSession daoSession = GreenDaoManager.getInstance().getDaoSession();
        long currentTimeMillis = System.currentTimeMillis();
        mPullEntities = daoSession.getPullEntityDao().queryBuilder().orderDesc(PullEntityDao.Properties.Priority).
                where(PullEntityDao.Properties.Type.eq(mActionType),
                        PullEntityDao.Properties.StartTime.le(currentTimeMillis),
                        PullEntityDao.Properties.EndTime.gt(currentTimeMillis)).list();
        List<LocalPullEntity> list = daoSession.getLocalPullEntityDao().queryBuilder().orderDesc(LocalPullEntityDao.Properties.PullTime).limit(1).list();
        if (list.size() > 0) {
            mLastTime = list.get(0).getPullTime();
        }
        List<Integer> pIds = new ArrayList<>();
        for (PullEntity p : mPullEntities) {
            pIds.add(p.getId());
        }
        if (pIds.size() > 0) {
            mLocalPullEntityList = daoSession.getLocalPullEntityDao().queryBuilder().orderDesc(LocalPullEntityDao.Properties.PullTime)
                    .where(LocalPullEntityDao.Properties.PullId.in(pIds)).list();
        }
        mRuleListEntityList = daoSession.getRuleListEntityDao().queryBuilder().list();
        return this;
    }
}